<?php

/*
 * 依门店代码抓hybris配货单
 */

$serverFilePath =realpath(dirname(__FILE__)); ;//realpath(dirname(__FILE__)); //$_SERVER["SCRIPT_FILENAME"];

$doc_dir = strrpos($serverFilePath, ''.DIRECTORY_SEPARATOR.'crontab');

$doc_dir = substr($serverFilePath, 0, $doc_dir + 1);   //project root

include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'lib/Config.php';
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'MaiscrmClass.php';
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'Logging.php';
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'GaoDeAPIClass.php';

set_time_limit(0);
error_reporting(E_ALL);
header("Content-type:text/html;charset:utf-8");

$config_ini = $doc_dir . 'config/config.ini';

$ini_array = parse_ini_file($config_ini, true);
$db_array = $ini_array['DB'];
$getWebsite = $ini_array['WebSite'];
$con = mysqli_init();

mysqli_real_connect($con, $db_array['host'], $db_array['id'], $db_array['pwd'], $db_array['database'], $db_array['port']);
mysqli_set_charset($con, $db_array['encoding']);

$log = new Logging();
$log->lfile('maiscrm_order');

$start = time() - (60);
$end = time();

//$start='2021-01-01 17:20';
//$end='2021-01-20 17:20';
  

$log->lwrite ('start:'.date('Y-m-d H:i:s',$start).', end:'.date('Y-m-d H:i:s',$end));


$page = 1;
$pageSize = 20;
$paramete = ['paid'=>'paid','unassigned'=>'unassigned','accepted'=>'accepted','type'=>'CLOSE_OPEN','express'=>'express','express2'=>'cityExpress','start'=>$start,'end'=>$end,'page'=>$page,'pageSize'=>$pageSize];
$Maiscrm = new MaiscrmClass($getWebsite['debug']);
$MaiscrmOrders = $Maiscrm->GetOrders($paramete);
$log->lwrite (json_encode($MaiscrmOrders, JSON_UNESCAPED_UNICODE));
if($MaiscrmOrders && count($MaiscrmOrders) > 0  && $MaiscrmOrders['total'] > 0){
    foreach ($MaiscrmOrders['items'] as $k => $value) {
        if (empty($value['campaigns']) || (isset($value['campaigns']['grouponStatus']) && $value['campaigns']['grouponStatus'] == 'success')){
            $shop_no    = $value['store']['code'];
            $ph_no      = $value['number'];
            $store_name = $value['store']['name'];
            $order_no   = $value['id'];
            $sql = "SELECT ph_no FROM `orders` WHERE `ph_no` = '{$ph_no}' AND `shop_no` = '{$shop_no}' ";
            $result = mysqli_query($con, $sql);
            if (!empty($result) && count($result) > 0) {
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
            }

            if($row || count($row) > 0){
                continue;
            }

            if(!$value['products'] || count($value['products'])  < 1){
                continue;
            }

			 $m_longitude = isset($value['contact']['address']['longitude']) ? $value['contact']['address']['longitude'] : '';
            $m_latitude = isset($value['contact']['address']['latitude']) ? $value['contact']['address']['latitude'] : '';
            $fee = isset($value['logistics']['fee']) ? $value['logistics']['fee']/100 : '';
            $field = [];
            $field['shop_no']           =   $shop_no;
            $field['shop_name']         =   $store_name;
            $field['ph_no']             =   $ph_no;
            $field['order_no']          =   $ph_no;
            $field['source']            =   '群脉商城';
            $field['buyer']             =   $value['memberId'];    # *
            $field['maiscrm_mid']       =   'check_num_maiscrm';
            $field['receiver']          =   $value['contact']['name'];
            $field['receiver_tel']      =   $value['contact']['phone'];
            $field['receiver_address']  =   address_str($value['contact']['address']);
            $field['customre_memo']     =   $value['message'];
            $field['seller_remarks']    =  $value['remarks'];
            $field['actual_pay']        =   $value['payAmount']/100;
            $field['pos_fee']           =   $fee;
            $field['order_time']        =   date('Y-m-d H:i:s',strtotime($value['paidAt']));
            $field['lng']               =   $m_longitude;
            $field['lat']               =   $m_latitude;
            if($value['method'] == 'express'){
                $field['delivery_time']     =   !empty($value['reservation']['time']) ? date('Y-m-d H:i:s', strtotime($value['reservation']['time'])) : date('Y-m-d').' 12:00';
            }else{
                $field['delivery_time']    =   date('Y-m-d H:i:s',strtotime($value['logistics']['expectDeliveryAt']));;
            }
            if($m_longitude && $m_latitude){
                $sql_s = "SELECT longitude,latitude FROM `xd_store` WHERE `store_id` = '{$shop_no}' ";
                $result_s = mysqli_query($con, $sql_s);
                $shop = '';
                if (!empty($result_s) && count($result_s) > 0) {
                    $shop = mysqli_fetch_array($result_s, MYSQLI_ASSOC);
                }
                if(is_array($shop) && count($shop) > 0){
                    if($shop['longitude'] && $shop['latitude']){
                        $distance = getdistanceAction($shop['longitude'], $shop['latitude'], $m_longitude, $m_latitude);
                    }
                    $log->lwrite ('地址：：：：：：：：：：：'.$shop['longitude'].','.$shop['latitude'].'----------'.$m_longitude.','.$m_latitude.'----------'.$distance.'：：：：：：：地址');
                }

            }
            $values = insertValue($field);

            $sql = "INSERT INTO `orders` {$values}";
            $result = mysqli_query($con, $sql);
            $log->lwrite (date('Y-m-d H:i:s')."门店:".$field['shop_no'].', addorder:' . $field['ph_no'] . "\n");
            $order_id = mysqli_insert_id($con);

            foreach ($value['products'] as $itm){
                $properties='';
                if (isset( $itm['spec']['properties'])){
                    $properties=join(",",$itm['spec']['properties']);
                }
                $p_field = [];
                $p_field['orders_id']       =   $order_id;
                $p_field['ph_no']           =   $ph_no;
                $p_field['product_no']      =   $itm['number'];
                $p_field['product_name']    =   $itm['name'];
                $p_field['delivery_type']   =   '门店配送';
                $p_field['pastry']          =   $properties;
                $p_field['qty']             =   $itm['total'];
                $p_field['unit_price']      =   $itm['price']/100;
                $p_field['amount']          =   $itm['totalAmount']/100;
                $values = insertValue($p_field);
                $sql = "INSERT INTO `orders_product` {$values}";
                $result = mysqli_query($con, $sql);
            }
        }
    }
}

function address_str(array $arr){
        $in = ['province','city','district','detail'];
        $str = '';
        foreach ($arr as $k => $itm){
            if(in_array($k,$in)){
                $str .= $itm;
            }
        }
        return $str;
}

function insertValue($arr) {
    $keys = array();
    $values = array();
    foreach ($arr as $k => $val) {
        $keys[] = "`" . $k . "`";
        $values[] = "'" . $val . "'";
    }
    $ks = implode(",", $keys);
    $vals = implode(",", $values);
    $re = "(" . $ks . ", createdt) values (" . $vals . ", now())";

    return $re;
}

 function mysql_escape($content) {
    if (!get_magic_quotes_gpc()) {

        if (is_array($content)) {
            foreach ($content as $key => $value) {
                $content[$key] = addslashes($value);
            }
        } else {
            $content = addslashes($content);
        }
    }
    return $content;
}


/**
 * 求两个已知经纬度之间的距离,单位为米
 * @param lng1 $ ,lng2 经度
 * @param lat1 $ ,lat2 纬度
 * @return float 距离，单位米
 */
function getdistanceAction($lng1, $lat1, $lng2, $lat2) {
    $radLat1 = deg2rad($lat1);
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
    return $s;
}


